//
//  FQQHeader.m
//  HouseClient
//
//  Created by 翁胜琼 on 2018/10/16.
//  Copyright © 2018 浙江房洽洽网络科技有限公司. All rights reserved.
//

#import "WSQTabSelectionView.h"
#import "Macros.h"
#import <Masonry/Masonry.h>

static NSUInteger const BtnBaseTag = 9090;

@interface WSQTabSelectionView()
{
    UIColor *_normalTextColor;
    UIColor *_selectedTextColor;
    UIFont *_normalTextFont;
    UIFont *_selectedTextFont;
    
}

@property (strong , nonatomic) NSMutableArray<UIButton *> *btnsArray;
@property (strong,nonatomic) UIButton *previousBtn;
@property (strong,nonatomic) CALayer *lineLayer;

@end

@implementation WSQTabSelectionView

- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray<NSString *> *)titles
{
    if (self = [super initWithFrame:frame])
    {
        _titles = titles;
        [self setupDefaultAppearance];
        [self setupUIWithTitles:titles];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setupDefaultAppearance];
}

- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state
{
    if (state == UIControlStateNormal)
    {
        _normalTextColor = color;
    }else if (state == UIControlStateSelected)
    {
        _selectedTextColor = color;
    }
    
    [self updateAppearance];
}

- (void)setTitleFont:(UIFont *)font forState:(UIControlState)state
{
    if (state == UIControlStateNormal)
    {
        _normalTextFont = font;
    }else if (state == UIControlStateSelected)
    {
        _selectedTextFont = font;
    }
    
    [self updateAppearance];
}


// 更新外观
- (void)updateAppearance
{
    __weak typeof(self) weakSelf = self;
    [self.btnsArray enumerateObjectsUsingBlock:^(UIButton * _Nonnull btn, NSUInteger idx, BOOL * _Nonnull stop) {
        __strong typeof(weakSelf) self = weakSelf;
        btn.titleLabel.font = self->_normalTextFont;
        [btn setTitleColor:self->_normalTextColor forState:UIControlStateNormal];
        [btn setTitleColor:self->_selectedTextColor forState:UIControlStateSelected];
        if (btn == self.previousBtn)
        {
            btn.titleLabel.font = self->_selectedTextFont;
        }
    }];

    [self setupLine];
}

// MARK: - setupUI
- (void)setupDefaultAppearance
{
    _normalTextFont = _normalTextFont !=nil ? _normalTextFont:[UIFont fontWithName:@"PingFang SC" size:14];
    _selectedTextFont = _selectedTextFont !=nil ? _selectedTextFont:[UIFont boldSystemFontOfSize:14];
    _normalTextColor = _normalTextColor != nil? _normalTextColor : UICOLORFROMHEX(0x333333);
    _selectedTextColor = _selectedTextColor != nil ? _selectedTextColor : UICOLORFROMHEX(0x333333);
    _lineHeight = _lineHeight != 0 ? _lineHeight : 3;
    _lineWidth = _lineWidth != 0 ? _lineWidth : 38;
    _lineColor = _lineColor != nil ? _lineColor : UICOLORFROMHEX(0xFA8C16);
}

- (void)setupUIWithTitles:(NSArray<NSString *> *)titles
{
    if (self.btnsArray.count > 0) [self resetBtns];
    self.btnsArray = [NSMutableArray array];
    [titles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self setupTitleBtnsWithTitle:obj idx:idx];
    }];
   
    [self setupLine];
    
    // 设置默认按钮
    //    [self btnAction:self.btnsArray[0]];
    [self.btnsArray[0] sendActionsForControlEvents:UIControlEventTouchUpInside];
    
}

// 删除原有按钮
- (void)resetBtns
{
    for (UIButton *btn in self.btnsArray) {
        [btn removeFromSuperview];
    }
    [self.lineLayer removeFromSuperlayer];
}

- (void)setupLine
{
    [self.lineLayer removeFromSuperlayer];
    
    // 判断是否有linelayer 配置，若是无则不需要配置
    if (self.lineConfigurationBlock)
    {
        self.lineLayer = self.lineConfigurationBlock();
    }else
    {
        self.lineLayer = [CALayer layer];
    }
    
    self.lineLayer.backgroundColor = _lineColor.CGColor;
    self.lineLayer.cornerRadius = _lineHeight / 2;
    CGFloat lineX = (self.btnsArray.firstObject.bounds.size.width - _lineWidth) / 2;
    _lineLayer.frame = CGRectMake(lineX, self.bounds.size.height - _lineHeight, _lineWidth, _lineHeight);
    [self.layer addSublayer:_lineLayer];
}

- (void)setupTitleBtnsWithTitle:(NSString *)title idx:(NSUInteger)idx
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:btn];
    
    btn.tag = BtnBaseTag + idx;
    CGFloat btnWidth = self.bounds.size.width / _titles.count;
    btn.frame = CGRectMake(idx * btnWidth, 0, btnWidth, self.bounds.size.height);
    
    @weakify(self)
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.height.equalTo(self);
        if (self->_btnsArray.lastObject != nil)
        {
            make.left.equalTo(self->_btnsArray.lastObject.mas_right);
        }else
        {
            make.left.equalTo(self);
        }
        make.width.equalTo(self).dividedBy(self->_titles.count);
    }];
    
    [self setupBtnAppearance:btn title:title];
    [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.btnsArray addObject:btn];
}

- (void)setupBtnAppearance:(UIButton *)btn title:(NSString *)title
{
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateSelected];
    btn.titleLabel.font = _normalTextFont;
    [btn setTitleColor:_normalTextColor forState:UIControlStateNormal];
    [btn setTitleColor:_selectedTextColor forState:UIControlStateSelected];
}

- (void)btnAction:(UIButton *)btn
{
    self.previousBtn.selected = false;
    self.previousBtn.titleLabel.font = _normalTextFont;
    btn.selected = true;
    btn.titleLabel.font = _selectedTextFont;
    NSUInteger idx = btn.tag - BtnBaseTag;
    [self.tabClickedSub sendNext:@(idx)];
    self.previousBtn = btn;
    
    [UIView animateWithDuration:0.3 animations:^{
        CGFloat lineX = (self.btnsArray.firstObject.bounds.size.width - self->_lineWidth) / 2;
        self.lineLayer.frame = CGRectMake(idx * btn.bounds.size.width + lineX, self.bounds.size.height - self->_lineHeight, self->_lineWidth, self->_lineHeight);
    }];
}

- (RACSubject *)tabClickedSub
{
    if (!_tabClickedSub)
    {
        _tabClickedSub = [RACSubject subject];
    }
    return _tabClickedSub;
}


// MARK: - setter
- (void)setTitles:(NSArray<NSString *> *)titles
{
    _titles = titles;
    [self setupUIWithTitles:titles];
}

- (NSInteger)selectedIndex
{
    return [self.btnsArray indexOfObject:self.previousBtn];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    [self btnAction:self.btnsArray[selectedIndex]];
}

//- (void)setLineConfigurationBlock:(lineConfigurationBlock)lineConfigurationBlock
//{
//    _lineConfigurationBlock = lineConfigurationBlock;
//    // 重新设置 line
//    [self setupLine];
//}
@end
